package com.yunxin.admin.system.infra.framework.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.CharPool;
import cn.hutool.core.util.IdUtil;
import com.yunxin.admin.system.application.OssService;
import com.yunxin.admin.system.application.dto.FileInfoDTO;
import com.yunxin.common.utils.AliYunOssUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * @author zero°
 * @since 2023-06-08
 */
@Service
@RequiredArgsConstructor
public class AliYunOssServiceImpl implements OssService {

    private static final int IMAGE_TYP = 2;

    private final AliYunOssConfig aliYunOssConfig;

    @Override
    public FileInfoDTO uploadFile(String suffix, InputStream inputStream, Integer type) {
        // 生成文件名(日期文件夹)
        String uuid = IdUtil.simpleUUID();
        String dir = type == IMAGE_TYP ? aliYunOssConfig.getOssImageDir() : aliYunOssConfig.getOssFileDir();
        String fileName = dir + DateUtil.format(LocalDateTime.now(), "yyyy/MM/dd") + CharPool.SLASH + uuid + CharPool.DOT + suffix;
        AliYunOssUtils aliYunOssUtils = new AliYunOssUtils(aliYunOssConfig.getEndpoint(), aliYunOssConfig.getAccessKeyId(), aliYunOssConfig.getAccessKeySecret());
        aliYunOssUtils.upload(aliYunOssConfig.getOssBucket(), fileName, inputStream);
        // 获取文件访问路径
        String fileUrl = aliYunOssConfig.getFrontDomain() + CharPool.SLASH + fileName;
        FileInfoDTO fileInfo = new FileInfoDTO();
        fileInfo.setName(fileName);
        fileInfo.setUrl(fileUrl);
        return fileInfo;
    }

    @Override
    public boolean deleteFile(String filePath) {
        Assert.notBlank(filePath, "删除文件路径不能为空");
        // 文件主机域名
        String fileHost =  aliYunOssConfig.getFrontDomain();
        // +1 是/占一个字符，截断左闭右开
        String fileName = filePath.substring(fileHost.length() + 1);
        AliYunOssUtils aliYunOssUtils = new AliYunOssUtils(aliYunOssConfig.getEndpoint(), aliYunOssConfig.getAccessKeyId(), aliYunOssConfig.getAccessKeySecret());
        aliYunOssUtils.deleteSingleObject(aliYunOssConfig.getOssBucket(), fileName);
        return true;
    }

}
